#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import socket
import os
import json
import time
import RPi.GPIO as GPIO

BUFSIZE = 1460

# gpio_svr_addr = '/tmp/gpio_socket'
svr_addr = socket.gethostname()
svr_port = 65512
ack = {}

cloud_addr = '101.133.173.227' # socket.gethostname()
cloud_port = 65510

local_log = '/home/pi/workspace/mishi.log'

try:
    log = open(local_log, 'a+')

    cloud_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # server.bind(gpio_svr_addr)
    server.bind((svr_addr, svr_port))
    server.listen(1)

    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)

    while True:
        cli_sock, cli_addr = server.accept()

        while True:
            data = cli_sock.recv(BUFSIZE)

            print('data ', data)
            if data:
                conf = json.loads(data)

                if isinstance(conf['gpio'], int) and isinstance(conf['level'], int):
                    print('gpio %d level %d' % (conf['gpio'], conf['level']))
                    GPIO.setup(conf['gpio'], GPIO.OUT)
                    GPIO.output(conf['gpio'], conf['level'])

                    cloud_sock.sendto(data, (cloud_addr, cloud_port))

                    logstr = '%s data %s\n' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), data)
                    log.write(logstr)
                    log.flush()

                    ack['status'] = 'ok'
                else:
                    err = 'type err'
                    print(err)
                    ack['status'] = err

                cli_sock.sendall(json.dumps(ack).encode())
            else:
                break

        cli_sock.close()

finally:

    GPIO.cleanup()
    server.close()
    cloud_sock.close()
    # os.remove(gpio_svr_addr)
    log.close()
